package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 查询所有的商户类型
     *
     * @return
     */
    @Override
    public List<ShopType> queryTypeList() {
        /*
        字符串类型存储
        //1.先在缓存中查询是否存在
        String key = "cache:shop-type";
        String typeJson = stringRedisTemplate.opsForValue().get(key);
        Long size = stringRedisTemplate.opsForList().size(key);
        //2. 存在，直接返回
        if (!StringUtils.isEmpty(typeJson)){
            log.info("在redis中查询到了");
            List<ShopType> typeList = JSONUtil.toList(typeJson, ShopType.class);
            return typeList;
        }
        //3. 不存在，
        log.info("没有在redis中查询到");
        List<ShopType> typeList = query().orderByAsc("sort").list();
        //4.加入redis缓存
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(typeList));
        return typeList;*/
        //List类型
        //1.先在缓存中查询是否存在
        String key = "cache:shop-type";
        List<String> typesStr = stringRedisTemplate.opsForList().range(key, 0, -1);
        //2. 存在，直接返回
        if (typesStr != null && !typesStr.isEmpty()) {
            // 直接将每个字符串转换为ShopType对象
            return typesStr.stream()
                    .map(jsonStr -> JSONUtil.toBean(jsonStr, ShopType.class))
                    .collect(Collectors.toList());
        }
        //3. 不存在，
        List<ShopType> typeList = query().orderByAsc("sort").list();
        //4.加入redis缓存
        List<String> collect = typeList.stream().map(JSONUtil::toJsonStr).collect(Collectors.toList());
        stringRedisTemplate.opsForList().rightPushAll(key, collect);
        return typeList;
    }
}
